import axios from 'axios';

const url = 'https://www.notion.so/api/v3/getCompletion';

const headers = {
  accept: 'application/json',
  'Notion-Version': '2022-06-28',
  'content-type': 'application/json',
  cookie:
    'token_v2=v02%3Auser_token_or_cookies%3AmfARm9RKpmT1T7CnRIsrHeHuC2lgNT6aOo6zY6fq1t9vpRAF_UJbzWklNy1m3dbnoJUFnqCnGRZhkwMxXhCu2UPWF4qYtU3mRo9swohclzL8KtaPv_b6wb2mJ5KWmv8t63Lw;',
};

function createParams(prompt) {
  let params = {
    id: '5256156e-a7e7-417e-97bd-8a6736cc7c51',
    context: {
      type: 'helpMeWrite',
      prompt: prompt,
      pageTitle: '',
      restContent: '',
      previousContent: '',
      // transcript: [
      //   { type: 'initial', pageTitle: '中文问答', pageContent: '' },
      //   { type: 'human', prompt: prompt },
      // ],
    },
    model: 'openai-3',
    spaceId: 'dce82e37-fb5c-4c15-a798-2cdaf6ad7d25',
    isSpacePermission: false,
  };

  return params;
}

export function getAIRes(prompt) {
  let params = createParams(prompt);
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'post',
      timeout: 20000,
      headers: { ...headers },
      data: params,
    }).then(res => {
      try {
        let items = res.data.split('\n');
        let chars = items.map(item => {
          if (item) {
            let item_json = JSON.parse(item);
            // console.log('===>', item)
            return item_json.completion;
          } else {
            return '';
          }
        });
        const result = chars.join('');
        console.log(result);
        resolve(result);
      } catch (e) {
        resolve(e);
      }
    });
  });
}